<template>
  <basic-container>
    <avue-crud
      :option="option"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button
          type="danger"
          v-show="btnDisplay"
          icon="el-icon-delete"
          plain
          v-if="permission.goods_delete"
          @click="handleDelete"
          >删 除
        </el-button>
      </template>

      <template #spec-form>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>自定义规格</span>
          </div>
          <template v-for="(spec, index) in form.spec">
            <el-row style="padding-bottom: 12px">
              <el-col :span="24" style="padding-bottom: 12px">
                <el-button
                  type="danger"
                  style="float: right"
                  @click.prevent="removeDomain(spec)"
                  v-show="!btnDisplay"
                  >删除</el-button
                >
              </el-col>
              <el-col :span="24" style="padding-bottom: 12px">
                <el-form-item
                  :label="'规格名称'"
                  :prop="'spec.' + index + '.name'"
                  :rules="{
                    required: true,
                    message: '规格名称不能为空',
                    trigger: 'blur',
                  }"
                >
                  <el-input v-model="spec.name" :disabled="btnDisplay"></el-input>
                </el-form-item>
              </el-col>
              <template v-for="(values, vindex) in spec.values">
                <el-col :span="12" style="padding-bottom: 12px">
                  <el-form-item
                    :label="'规格值'"
                    :prop="'spec.' + index + '.values.' + vindex + '.kvalue'"
                    :rules="{
                      required: true,
                      message: '规格值不能为空',
                      trigger: 'blur',
                    }"
                  >
                    <el-input v-model="values.kvalue" :disabled="btnDisplay"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2" style="padding-left: 12px">
                  <el-button
                    v-show="!btnDisplay"
                    type="danger"
                    size="small"
                    @click.prevent="removeValue(spec.values, values)"
                    >删除规格值</el-button
                  >
                </el-col>
              </template>
              <el-col :span="12" style="text-align: center">
                <el-button type="primary" @click.prevent="addValue(spec)" v-show="!btnDisplay"
                  >新增规格值</el-button
                >
              </el-col>
            </el-row>
          </template>
          <el-button type="primary" @click="addSpec" v-show="!btnDisplay">新增规格</el-button>
        </el-card>
      </template>
      <template #specDetail-form>
        <el-table :data="tableData" v-if="form.spec.length > 0">
          <el-table-column
            v-for="title in tableTitleList"
            :prop="title.prop"
            :label="title.name"
            align="center"
            :key="title.prop"
            :index="title.index"
          >
            <template v-if="title.prop === 'cost'" #default="{ row, $index }">
              <el-input-number
                :precision="2"
                :step="0.01"
                :min="0"
                v-model="row.cost"
                style="position: relative"
                :disabled="btnDisplay"
              />
            </template>
            <template v-if="title.prop === 'price'" #default="{ row, $index }">
              <el-input-number
                :precision="2"
                :step="0.01"
                :min="0"
                v-model="row.price"
                style="position: relative"
                :disabled="btnDisplay"
              />
            </template>
            <template v-if="title.prop === 'weight'" #default="{ row, $index }">
              <el-input-number
                :min="0"
                :disabled="btnDisplay"
                v-model="row.weight"
                style="position: relative"
              />
            </template>
            <template v-if="title.prop === 'quantity'" #default="{ row, $index }">
              <el-input-number
                :min="0"
                :disabled="btnDisplay"
                v-model="row.quantity"
                style="position: relative"
              />
            </template>
            <template v-if="title.prop === 'sn'" #default="{ row, $index }">
              <el-input
                type="text"
                :disabled="btnDisplay"
                v-model="row.sn"
                style="position: relative"
              />
            </template>
          </el-table-column>
        </el-table>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/shop/goods';
import { getCategoryTree } from '@/api/shop/category';
import option from '@/option/shop/goods';
import { mapGetters } from 'vuex';

export default {
  data() {
    return {
      form: {
        spec: [],
        image:[],
        video:[],
      },
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: option,
      data: [],
      tableTitleList: [],
      tableData: [],
      detailTableData: [],
      btnDisplay: false,
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.goods_add, false),
        viewBtn: this.validData(this.permission.goods_view, false),
        delBtn: this.validData(this.permission.goods_delete, false),
        editBtn: this.validData(this.permission.goods_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  watch: {
    'form.spec': {
      deep: true,
      handler(newObj, oldObj) {
        this.tableData = [];
        this.tableTitleList = [];
        this.tableTitleList = [
          { prop: 'cost', name: '成本价(元)' },
          { prop: 'price', name: '价格(元)' },
          { prop: 'weight', name: '重量(KG)' },
          { prop: 'quantity', name: '库存' },
          { prop: 'sn', name: '货号' },
        ];
        if (!newObj) {
          return;
        }
        for (let i = 0; i < newObj.length; i++) {
          let ojb = newObj[i];
          if (ojb) {
            let talbleTitle = {
              prop: ojb.name + '_custom',
              name: ojb.name,
            };
            this.tableTitleList.unshift(talbleTitle);
          }
        }
        let result = [{}];
        let arrays = this.form.spec;
        if (arrays.length > 0) {
          arrays.map(x => {
            if ('values' in x && 'name' in x) {
              let res = [];
              result.map(y => {
                x.values.map(z => {
                  res.push({ ...y, [x.name + '_custom']: z });
                });
              });
              result = res;
            }
          });
        }
        for (let i = 0; i < result.length; i++) {
          let obj = result[i];
          let row = {
            cost: 0,
            price: 0,
            weight: 0,
            quantity: 0,
            sn: '',
          };
          for (let key in obj) {
            row[key] = obj[key].kvalue;
          }
          if (Object.keys(obj).length > 0) {
            this.tableData.push(row);
          }
        }
      },
    },
  },
  methods: {
    initData() {
      getCategoryTree().then(res => {
        const column = this.findObject(this.option.column, 'categoryId');
        column.dicData = res.data.data;
      });
    },
    addSpec() {
      this.form.spec.push({
        value: '',
        key: Date.now(),
      });
    },
    removeDomain(item) {
      let index = this.form.spec.indexOf(item);
      if (index !== -1) {
        this.form.spec.splice(index, 1);
      }
    },
    addValue(item) {
      if ('values' in item) {
        item.values.push({
          kvalue: '',
          key: Date.now(),
        });
      } else {
        item.values = [];
        item.values.push({
          kvalue: '',
          key: Date.now(),
        });
      }
    },
    removeValue(items, item) {
      let index = items.indexOf(item);
      if (index !== -1) {
        items.splice(index, 1);
      }
    },
    rowSave(row, done, loading) {
      let images = [];
      let videos = [];
      for (let i = 0; i < row.image.length; i++) {
        let image = {
          mediumType: '0',
          url: row.image[i],
        };
        images.push(image);
      }
      for (let i = 0; i < row.video.length; i++) {
        let video = {
          mediumType: '1',
          url: row.video[i],
        };
        videos.push(video);
      }
      if (row.id === '') {
        const params = {
          name: row.name,
          cost: row.cost,
          price: row.price,
          sellingPoint: row.sellingPoint,
          categoryId: row.categoryId,
          goodsType: row.goodsType,
          goodsUnitId: row.goodsUnitId,
          intro: row.intro,
          marketEnbale: row.marketEnbale,
          sn: row.sn,
          recommend: row.recommend,
          goodsSkus: this.tableData,
          goodsImageVOList: images,
          goodsVideoVOList: videos,
        };
        add(params).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
            done();
          },
          error => {
            loading();
            window.console.log(error);
          }
        );
      }
    },
    rowUpdate(row, index, done, loading) {
      let images = [];
      let videos = [];
      for (let i = 0; i < row.image.length; i++) {
        let image = {
          mediumType: '0',
          url: row.image[i],
        };
        images.push(image);
      }
      for (let i = 0; i < row.video.length; i++) {
        let video = {
          mediumType: '1',
          url: row.video[i],
        };
        videos.push(video);
      }
      const params = {
        id: row.id,
        name: row.name,
        cost: row.cost,
        price: row.price,
        sellingPoint: row.sellingPoint,
        categoryId: row.categoryId,
        goodsType: row.goodsType,
        goodsUnitId: row.goodsUnitId,
        intro: row.intro,
        marketEnbale: row.marketEnbale,
        sn: row.sn,
        recommend: row.recommend,
        goodsSkus: this.tableData,
        goodsImageVOList: images,
        goodsVideoVOList: videos,
      };
      update(params).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.form.spec = [];
      if (['add', 'edit'].includes(type)) {
        this.initData();
        this.btnDisplay = false;
      }
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form.name = res.data.data.name;
          this.form.cost = res.data.data.cost;
          this.form.price = res.data.data.price;
          this.form.sellingPoint = res.data.data.sellingPoint;
          this.form.categoryId = res.data.data.categoryId;
          this.form.goodsType = res.data.data.goodsType;
          this.form.goodsUnitId = res.data.data.goodsUnitId;
          this.form.intro = res.data.data.intro;
          this.form.marketEnbale = res.data.data.marketEnbale;
          this.form.sn = res.data.data.sn;
          this.form.recommend = res.data.data.recommend;
          const images = [];
          const videos = [];
          if (res.data.data.goodsImageVOList) {
            for (let i = 0; i < res.data.data.goodsImageVOList.length; i++) {
              images.push(res.data.data.goodsImageVOList[i].url);
            }
            this.form.image = images;
          }
          if (res.data.data.goodsVideoVOList) {
            for (let i = 0; i < res.data.data.goodsVideoVOList.length; i++) {
              videos.push(res.data.data.goodsVideoVOList[i].url);
            }           
            this.form.video = videos;
          }
          
          let skus = res.data.data.goodsSkus;
          let temp = [];
          let tempObj = {};
          for (let i = 0; i < skus.length; i++) {
            let obj = skus[i];
            for (let key in obj) {
              if (key.includes('_custom')) {
                if (key in tempObj) {
                  if (!tempObj[key].includes(obj[key])) {
                    tempObj[key].push(obj[key]);
                  }
                } else {
                  tempObj[key] = [obj[key]];
                }
              }
            }
          }
          for (let key in tempObj) {
            let o = {
              value: '',
              key: Date.now(),
              name: key.split('_custom').join(''),
              values: [],
            };
            for (let i = 0; i < tempObj[key].length; i++) {
              let m = {
                kvalue: tempObj[key][i],
                key: Date.now(),
              };
              o.values.push(m);
            }
            temp.push(o);
          }
          for (let i = 0; i < skus.length; i++) {
            let obj = skus[i];
            this.detailTableData.push(obj);
          }
          this.form.spec = temp;

          this.$nextTick(() => {
            this.tableData = skus;
          });
          if (['view'].includes(type)) {
            this.btnDisplay = true;
          }
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const { name } = this.query;

      let values = {
        name_like: name,
      };

      getList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>
<style>
  .avue-upload--upload .el-upload-list {
    margin-top: 4px;
}
</style>

